<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="课程分类" prop="serviceIds">
        <el-cascader
          class="w-100%"
          v-model="formData.serviceIds"
          :options="serviceClassTree"
          :props="{ label: 'name', value: 'id' }"
          filterable/>
      </el-form-item>
      <el-form-item label="课程人数" prop="peopleCount">
        <el-select v-model="formData.peopleCount" placeholder="请选择课程人数">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_COACH_SERVICE_PEOPLE_COUNT)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程时间" prop="serviceTime">
        <el-select v-model="formData.serviceTime" placeholder="请选择课程时间">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_COACH_SERVICE_TIME)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程价格" prop="price">
        <el-input-number style="width: 100%" :min="0" v-model="formData.price" placeholder="请输入课程价格" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请输入排序" />
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-radio-group v-model="formData.auditStatus">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.BUSINESS_AUDIT_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="formData.auditStatus === 20" label="拒绝原因" prop="refuseCause">
        <el-input type="textarea" :rows="6" v-model="formData.refuseCause" placeholder="请输入拒绝原因" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { CoachPlanApi, CoachPlan } from '@/api/business/coachplan'
import { CoachApi } from '@/api/business/coach'
import {ServiceClassApi} from "@/api/business/serviceclass";
import {handleTree} from "@/utils/tree";

/** 教练课程方案 表单 */
defineOptions({ name: 'CoachPlanForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  coachId: undefined,
  serviceIds: [],
  auditStatus: undefined,
  sort: undefined,
  peopleCount: undefined,
  serviceTime: undefined,
  price: undefined,
  refuseCause: undefined,
})
const formRules = reactive({
  serviceIds: [{ required: true, message: '课程分类不能为空', trigger: 'blur' }],
  auditStatus: [{ required: true, message: '审核状态不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
  peopleCount: [{ required: true, message: '课程人数不能为空', trigger: 'change' }],
  serviceTime: [{ required: true, message: '课程时间不能为空', trigger: 'change' }],
  price: [{ required: true, message: '课程价格不能为空', trigger: 'blur' }],
  refuseCause: [{ required: true, message: '拒绝原因不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

const serviceClassTree = ref([])
/** 打开弹窗 */
const open = async (type: string, id?: number, coachId: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 获取该教练下的服务类目
  serviceClassTree.value = []
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CoachPlanApi.getCoachPlan(id)
      formData.value.price = formData.value.price / 100

      const data = await CoachApi.getCoachServiceClassByCoachId(formData.value.coachId)
      serviceClassTree.value = handleTree(data, 'id', 'parentId')
    } finally {
      formLoading.value = false
    }
  }else {
    formData.value.auditStatus = 0
  }
  formData.value.coachId = coachId
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CoachPlan
    data.price = data.price * 100
    if (formType.value === 'create') {
      await CoachPlanApi.createCoachPlan(data)
      message.success(t('common.createSuccess'))
    } else {
      await CoachPlanApi.updateCoachPlan(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    coachId: undefined,
    serviceIds: [],
    auditStatus: undefined,
    sort: undefined,
    peopleCount: undefined,
    serviceTime: undefined,
    price: undefined,
    refuseCause: undefined,
  }
  formRef.value?.resetFields()
}
</script>
